package blue.http.internal.core.plugin;

import blue.base.core.common.Tuple;
import blue.base.core.util.AssertUtil;
import blue.http.core.exception.HttpServerException;
import blue.http.core.plugin.HandlerProvider;
import blue.http.core.plugin.HandlerRegister;
import blue.http.internal.core.net.DefaultHttpServerBuilder;
import blue.http.internal.core.parser.ParserFactory;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.util.ArrayList;
import java.util.List;

/**
 * @author Jin Zheng
 * @date 2021-09-16
 */
public class ProviderManager {
	private static Logger logger = LoggerFactory.getLogger(DefaultHttpServerBuilder.class);

	private final DefaultHttpServerBuilder builder;
	private final HandlerRegister handlerRegister;
	private final List<Tuple> handlerList = new ArrayList<>();

	public ProviderManager(DefaultHttpServerBuilder builder) {
		this.builder = builder;
		this.handlerRegister = new DefaultHandlerRegistry(builder);
	}

	public void parse() {
		ParserFactory parserFactory = builder.getParserFactory();
		for (var handler : handlerList) {
			parserFactory.parse(handler.getFirst(), handler.getSecond());
		}
	}

	public void addHandler(Object handler, Class<?> clazz) {
		handlerList.add(new Tuple(handler, clazz));
	}

	public void addProvider(Object provider) {
		AssertUtil.notNull(provider, "Provider");
		if (provider instanceof HandlerProvider) {
			((HandlerProvider) provider).handle(handlerRegister);
		} else {
			throw new HttpServerException("Unknown Provider");
		}
	}

}
